/* 上传控件
 * UploadComponent.jsx
 */
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';

import '../static/css/uploadComponent.css';

import {
		clearPageIdArr,
		uploadAudioAct,listMusic,musicNextPage,musicPrePage,categoryMusic,
		uploadFileAct,listFile,fileNextPage,filePrePage,categoryFile,
		listImage,uploadImage,clearImagelist,imgNextPage,imgPrePage,categoryImage,
	   } from '../actions/FileHandleAction';
import {showMessagePopup} from '../utils/H5helper';


class ItemListComp extends Component{

	clickItem(name,src){
		this.props.itemClick(src,name);
	}

	//点击上一页
	prePage(e){
		e.preventDefault()|| e.stopPropagation();//阻止冒泡
		if(this.props.pageIdArr.size>0){
			const maxId=this.props.pageIdArr.last();//获取上一页的最大id
			//this.props.dispatch(musicPrePage(this.props.categoryId,maxId+1,10));
			this.props.prePage(maxId+1);
		}
	}
	
	//点击下一页
	nextPage(e){
		e.preventDefault()|| e.stopPropagation();//阻止冒泡
		//获取当前页的最大id和最小id，用于计算上一页
		const maxId=this.props.datalist.get(0).get('id');//当前页的最大id
		const minId=this.props.datalist.get(this.props.datalist.size-1).get('id');//当前页的最小id
		if(maxId!=this.props.pageIdArr.last()){//当前页的最大id与上一页相同，已是最后一页
			//this.props.dispatch(musicNextPage(maxId,this.props.categoryId,minId,10));
			this.props.nextPage(maxId,minId);
		}
	}


	render(){
		const itemStyle={
		    width: '90px',height: '90px',display:'flex',backgroundColor: '#F5F5F5',alignItems: 'center',
			justifyContent: 'center',position: 'relative',cursor:'pointer'
		}
		const itemNameStyle={
			    display: 'block',fontSize: '12px',textAlign: 'center',width: '90%',margin: '0 5%',height: '17px',
			    position: 'absolute',bottom: '2px',left: 0,color: '#666',overflow: 'hidden',textOverflow: 'ellipsis',whiteSpace: 'nowrap'
		}
		let divRows=Array();
		if(this.props.type=='music'){
			this.props.datalist.forEach(obj=>{
			divRows.push(<div key={obj.get('id')} className="column">
						<a style={itemStyle} onClick={()=>{this.clickItem(obj.get('name'),obj.get('url'))}}>
							<i style={{fontSize:'2.5rem'}} className="music icon"></i>
							<span style={itemNameStyle}>{obj.get('name')}</span>
						</a>
					  </div>);
			});

		}else if(this.props.type=='image'){
			this.props.datalist.forEach(obj=>{
				divRows.push(<div key={obj.get('id')} className="column">
							<img className="ui image" style={{cursor:'pointer',width: '90px',height: '90px'}} 
								onClick={()=>{this.clickItem(obj.get('name'),obj.get('url'))}} src={obj.get('url')} />
					  </div>);
			});
		}else if(this.props.type=='file'){
			this.props.datalist.forEach(obj=>{
			divRows.push(<div key={obj.get('id')} className="column">
						<a style={itemStyle} onClick={()=>{this.clickItem(obj.get('name'),obj.get('url'))}}>
							<i style={{fontSize:'2.5rem'}} className="file outline icon"></i>
							<span style={itemNameStyle}>{obj.get('name')}</span>
						</a>
					  </div>);
			});
		}
		
		//上一页，下一页
		let pagePre='';
		if(this.props.pageIdArr.size>0){
			pagePre=(<span onClick={(e)=>this.prePage(e)} style={{cursor:'pointer'}}>上一页</span>);
		}
		let pageNext=(<span onClick={(e)=>this.nextPage(e)} style={{cursor:'pointer',marginLeft:10}}>下一页</span>);
		if(this.props.datalist.size==0 || this.props.datalist.size<10){
			pageNext='';
		}

		return(
			<div style={{marginTop:'15px'}}>
				<div className="ui five column grid">
					{divRows}
				</div>
				<div style={{marginTop:10,textAlign:'right'}}>{pagePre}{pageNext}</div>
			</div>
		);
	}
}

class CategoryListComp extends Component{

	constructor(props){
		super(props);
		this.state={activeCat:''};
	}

	categoryClick(categoryId){
		this.setState({activeCat:categoryId})
		this.props.categoryClick(categoryId);
	}

	render(){
		let items=Array();
		const normalStyle={
			marginRight:'10px',
			cursor:'pointer',
			display: 'inline-block',
		    color: '#666',
		    margin: '2px 0',
		    padding: '2px 8px',
		    borderRadius: '20px',
		    backgroundColor: '#fff'
		};
		const selectStyle={...normalStyle,backgroundColor:'#efefef'}

		if(this.props.datalist && this.props.datalist.size>0){
			this.props.datalist.forEach(obj=>{
				let aStyle=normalStyle;
				if(this.state.activeCat==obj.get('id'))
					aStyle=selectStyle;
				items.push(
					<a style={aStyle} key={obj.get('id')} onClick={()=>this.categoryClick(obj.get('id'))}>{obj.get('name')}</a>
				);
			});
		}
		return (
			<div style={{display:'inline-block',height: '32px',verticalAlign:'top',marginLeft:'15px',paddingTop:'5px'}}>
				<a style={this.state.activeCat==''?selectStyle:normalStyle} onClick={()=>this.categoryClick('')}>全部</a>
				{items}
			</div>
		)
	}
}

class UploadHeadComp extends Component{
	constructor(props){
		super(props);
		this.state={uploading:false};
	}

	doUpload(){
		this.setState({uploading:true});
		let input = document.querySelector('#'+this.props.inputFileId);
		this.props.uploadFile(input.files,(res)=>{
			console.log('set uploading end');
			this.setState({uploading:false});
		});
	}

	openFileWin(){//弹出文件选择框
		document.querySelector('#'+this.props.inputFileId).click();
	}

	render(){
		const uploadMsg=this.state.uploading?(<div className="ui small active inline loader"></div>):(<span>({this.props.fileType})</span>);
		let inputProps={
			onChange:this.doUpload.bind(this)
		}
		if(this.props.multiple) inputProps.multiple="multiple";
		if(this.props.acceptType) inputProps.accept=this.props.acceptType;
		return(
			<div className="img-upload">
				<a className="img-upload-btn" href="javascript:void(0)" style={{position:'relative',cursor:'pointer'}}>
					<div className="webuploader-pick"><i className="cloud Upload icon"></i>&nbsp;{this.props.btnName}</div>
					<div style={{position: 'absolute',top: '0px', left: '0px', width: '110px', height: '32px', overflow: 'hidden',bottom: 'auto', right: 'auto'}}>
						<input id={this.props.inputFileId} type="file" name="file" className="webuploader-element-invisible" {...inputProps} />
						<label style={{opacity:0,width:'100%',height:'100%', display:'block', cursor:'pointer', background: 'rgb(255, 255, 255)'}} onClick={()=>this.openFileWin()}></label>
					</div>
				</a>
				<span style={{display:'inline-block',height: '32px',lineHeight: '32px',verticalAlign:'top',marginLeft:'10px'}}>{uploadMsg}</span>
				<CategoryListComp datalist={this.props.categoryList} categoryClick={this.props.categoryClick} />
			</div>
		)
	}
}


class FileUploadComp extends Component{
	constructor(props){
		super(props);
		this.state={currenCategory:''}
	}

	uploadFile(files,callback){
		let categoryId=this.state.currenCategory;
		console.log(this.props.categoryList);
		if(categoryId=='' && this.props.categoryList.size==0){
			if(callback) callback();
			showMessagePopup('没有分类信息，请先设置分类');
			return;
		}
		if(categoryId==''){
			categoryId=this.props.categoryList.get(0).get('id');
		}
		this.props.dispatch(uploadFileAct(files,categoryId,callback));
	}

	itemClick(src,name){
		this.props.itemClick(src,name);
	}

	prePage(maxId){
		this.props.dispatch(filePrePage(this.state.currenCategory,maxId,10));
	}

	nextPage(maxId,minId){
		this.props.dispatch(fileNextPage(maxId,this.state.currenCategory,minId,10));
	}

	categoryClick(categoryId){
		this.props.dispatch(listFile(categoryId,null,10));
	}

	render(){
		const headProps={
			btnName:"上传文件",
			fileType:".*",
			multiple:false,
			inputFileId:'fileInput',
			categoryList:this.props.categoryList,
			uploadFile:this.uploadFile.bind(this),
			categoryClick:this.categoryClick.bind(this)
		}
		const listProps={
			type:'file',
			pageIdArr:this.props.pageIdArr,
			datalist:this.props.datalist,
			itemClick:this.itemClick.bind(this),
			prePage:this.prePage.bind(this),
			nextPage:this.nextPage.bind(this)
		}
		return(
				<div className="image-list-wp">
					<UploadHeadComp {...headProps} />
					<ItemListComp {...listProps} />
				</div>
			);
	}
}


class MusicUploadComp extends Component{
	constructor(props){
		super(props);
		this.state={currenCategory:''}
	}

	uploadFile(files,callback){
		let categoryId=this.state.currenCategory;
		if(categoryId=='' && this.props.categoryList.size==0){
			if(callback) callback();
			showMessagePopup('没有分类信息，请先设置分类');
			return;
		}
		if(categoryId==''){
			categoryId=this.props.categoryList.get(0).get('id');
		}
		this.props.dispatch(uploadAudioAct(files,categoryId,callback));
	}

	itemClick(src,name){
		this.props.itemClick(src,name);
	}

	prePage(maxId){
		this.props.dispatch(musicPrePage(this.state.currenCategory,maxId,10));
	}

	nextPage(maxId,minId){
		this.props.dispatch(musicNextPage(maxId,this.state.currenCategory,minId,10));
	}
	categoryClick(categoryId){
		this.setState({currenCategory:categoryId});
		this.props.dispatch(listMusic(categoryId,null,10));
	}
	render(){
		const headProps={
			btnName:"上传音频",
			fileType:".mp3",
			multiple:false,
			acceptType:'audio/mpeg',
			inputFileId:'musicInput',
			categoryList:this.props.categoryList,
			categoryClick:this.categoryClick.bind(this),
			uploadFile:this.uploadFile.bind(this)
		}
		const listProps={
			type:'music',
			pageIdArr:this.props.pageIdArr,
			datalist:this.props.datalist,
			itemClick:this.itemClick.bind(this),
			prePage:this.prePage.bind(this),
			nextPage:this.nextPage.bind(this)
		}
		return(
				<div className="image-list-wp">
					<UploadHeadComp {...headProps} />
					<ItemListComp {...listProps} />
				</div>
			);
	}
}

class ImageUploadComp extends Component{

	constructor(props){
		super(props);
		this.state={currenCategory:''}
	}

	uploadFile(files,callback){
		let categoryId=this.state.currenCategory;
		if(categoryId=='' && this.props.categoryList.size==0){
			if(callback) callback();
			showMessagePopup('没有分类信息，请先设置分类');
			return;
		}
		if(categoryId==''){
			categoryId=this.props.categoryList.get(0).get('id');
		}
		this.props.dispatch(uploadImage(files,categoryId,callback));
	}

	itemClick(src,name){
		this.props.itemClick(src,name);
	}

	prePage(maxId){
		this.props.dispatch(imgPrePage(this.state.currenCategory,maxId,10));
	}

	nextPage(maxId,minId){
		this.props.dispatch(imgNextPage(maxId,this.state.currenCategory,minId,10));
	}

	categoryClick(categoryId){
		this.setState({currenCategory:categoryId});
		this.props.dispatch(listImage(categoryId,null,10));
	}

	render(){
		const headProps={
			btnName:"上传图片",
			fileType:".jpg/.png",
			multiple:this.props.multiple,
			acceptType:'image/*',
			inputFileId:'imgInput',
			categoryList:this.props.categoryList,
			uploadFile:this.uploadFile.bind(this),
			categoryClick:this.categoryClick.bind(this)
		}
		const listProps={
			type:'image',
			pageIdArr:this.props.pageIdArr,
			datalist:this.props.datalist,
			itemClick:this.itemClick.bind(this),
			prePage:this.prePage.bind(this),
			nextPage:this.nextPage.bind(this)
		}
		return(
				<div className="image-list-wp">
					<UploadHeadComp {...headProps} />
					<ItemListComp {...listProps} />
				</div>
			);
	}
}


class UploadComponent extends Component{
	constructor(props){
		super(props);
		this.state={activeTab:''};
	}

	componentDidMount(){
		//$('.uploadComponent .item').tab();
	}

	componentWillMount(){
		this.props.dispatch(categoryImage());
		this.props.dispatch(categoryMusic());
		this.props.dispatch(categoryFile());
	}

	tabClick(name){
		this.setState({activeTab:name});
		this.props.dispatch(clearPageIdArr());
		if(name=='image'){
			this.props.dispatch(listImage(null,null,10));
		}
		if(name=='music'){
			this.props.dispatch(listMusic(null,null,10));
		}
		if(name=='file'){
			this.props.dispatch(listFile(null,null,10));
		}
	}

	render(){
		const imgProps={
			datalist:this.props.imglist,
			pageIdArr:this.props.pageIdArr,//用于分页
			dispatch:this.props.dispatch,
			itemClick:this.props.imgClick,
			multiple:this.props.multiple,
			categoryList:this.props.imageCatetory
		}
		
		const musicProps={
			dispatch:this.props.dispatch,
			datalist:this.props.musiclist,
			pageIdArr:this.props.pageIdArr,
			itemClick:this.props.musicItemClick,
			categoryList:this.props.musicCatetory
		}

		const fileProps={
			datalist:this.props.fileList,
			dispatch:this.props.dispatch,
			pageIdArr:this.props.pageIdArr,
			itemClick:this.props.fileItemClick,
			categoryList:this.props.fileCatetory
		}

		let tabs=Array();
		let tabContent=Array();
		let activeTab=this.state.activeTab;
		if(activeTab==''){
			activeTab=this.props.showTabs[0];
		}
		
		for(let item of this.props.showTabs){
			let tabClass="item";
			let contentClass="ui bottom attached tab segment";
			if(item=='image'){
				if(activeTab=='image'){
					tabClass="item active";
					contentClass="ui bottom attached active tab segment";
				}
				const imageTab=(<a key="image" className={tabClass} data-tab="first" onClick={()=>this.tabClick('image')}>图片</a>);
				const imageCont=(
					<div className={contentClass} key="first" data-tab="first" style={{width:this.props.width-50,border:'none'}}>
					  <ImageUploadComp {...imgProps} />
					</div>
				);
				tabs.push(imageTab);
				tabContent.push(imageCont);
			}
			if(item=='file'){
				if(activeTab=='file'){
					tabClass="item active";
					contentClass="ui bottom attached active tab segment";
				}
				const fileTab=(<a className={tabClass} key="file" data-tab="second" onClick={()=>this.tabClick('file')}>文件</a>);
				const fileCont=(
						<div className={contentClass} key="second" data-tab="second" style={{width:this.props.width-50,border:'none'}}>
						  <FileUploadComp {...fileProps}/>
						</div>
					);
				tabs.push(fileTab);
				tabContent.push(fileCont);
			}
			if(item=='music'){
				if(activeTab=='music'){
					tabClass="item active";
					contentClass="ui bottom attached active tab segment";
				}
				const musicTab=(<a className={tabClass} key="music" data-tab="third" onClick={()=>this.tabClick('music')}>音频</a>);
				const musicCont=(
						<div className={contentClass} key="third" data-tab="third" style={{width:this.props.width-50,border:'none'}}>
						  <MusicUploadComp {...musicProps}/>
						</div>
					);
				tabs.push(musicTab);
				tabContent.push(musicCont);
			}
		}
		return(
			<div style={{width:this.props.width,height:this.props.height}}>
				<div className="ui top attached tabular menu uploadComponent" style={{width:this.props.width-30}}>
				  {tabs}
				</div>
				{tabContent}
			</div>
		);
	}
}


export default connect(state=>{ 
	return {
		imglist:state.app.uploadFileReducer.imageList,
		musiclist:state.app.uploadFileReducer.musicList,
		fileList:state.app.uploadFileReducer.fileList,
		pageIdArr:state.app.uploadFileReducer.pageIdArr,
		imageCatetory:state.app.uploadFileReducer.imageCatetory,
		musicCatetory:state.app.uploadFileReducer.musicCatetory,
		fileCatetory:state.app.uploadFileReducer.fileCatetory
	} 
} )(UploadComponent);



/* 分页展示图片的组件
 * props的参数：row 一页显示row行， col 每行显示col张图片
 * 				datalist 数组类型，图片数据
 *				imageClick 点击图片触发的事件
 页面自动分页
class ImagesPageShowComp extends Component{
	constructor(props){
		super(props);
		this.pageImgData=Immutable.List();//当前页面数据
		this.pageNum=10;//一页显示的图片数量
	}

	//计算页数，total明细总数，pageNum每页的明细数
	computePages(total,pageNum){
		if(total%pageNum!=0)
			return (parseInt(total/pageNum)+1);
		else
			return parseInt(total/pageNum); 
	}

	//把datalist变成分页好的数据
	pageDatalist(datalist,pages,row,col){
		let pagelist=Immutable.List();
		let n=0;
		for(let i=0;i<pages;i++){
			let pageData=Immutable.List();//单个页面数据
			for(let j=0;j<row;j++){
				let rowData=Immutable.List();//单行数据
				for(let k=0;k<col;k++){
					const data=datalist.get(n);
					if(data)
						rowData=rowData.push(data);
					n++;
				}
				pageData=pageData.push(rowData);
			}
			pagelist=pagelist.push(pageData);
		}
		return pagelist;
	}

	//获取当前页的数据
	pageData(currentPage,datalist=null){
		if(datalist!=null){
			const res=datalist.get(currentPage-1);
			if(res==null) return Immutable.List();
			return res;
		}
	}

	//点击上一页
	prePage(e){
		e.preventDefault()|| e.stopPropagation();//阻止冒泡
		if(this.props.pageMaxIdArr.size>0){
			const maxId=this.props.pageMaxIdArr.last();//获取上一页的最大id
			this.props.dispatch(prePage(this.props.categoryId,maxId+1,this.pageNum));
		}
	}

	//点击下一页
	nextPage(e){
		e.preventDefault()|| e.stopPropagation();//阻止冒泡
		//获取当前页的最大id和最小id，用于计算上一页
		const maxId=this.props.datalist.get(0).get('id');//当前页的最大id
		const minId=this.props.datalist.get(this.props.datalist.size-1).get('id');//当前页的最小id
		if(maxId!=this.props.pageMaxIdArr.last()){//当前页的最大id与上一页相同，已是最后一页
			this.props.dispatch(nextPage(maxId,this.props.categoryId,minId,this.pageNum));
		}
	}

	render(){
		const datalist=this.props.datalist;
		this.pageNum=this.props.row*this.props.col;
		const totalPageNum=this.computePages(datalist.size,this.pageNum);
		const pageList=this.pageDatalist(datalist,totalPageNum,this.props.row,this.props.col);
		//this.pageImgData=this.pageData(this.state.currentPage,pageList);
		if(pageList.get(0)!=null) this.pageImgData=pageList.get(0);

		//图片展示数据
		let divRows=Array();
		let k=1;
		this.pageImgData.forEach(item=>{
			let imgCols=Array();
			item.forEach(obj=>{
				const name=obj.get('name'),src=obj.get('url'),id=obj.get('id');
				const img=( <img className="ui image" style={{cursor:'pointer',maxHeight:this.props.imgMaxHeight}} key={id} onClick={()=>this.props.imgClick(src,name)} src={src} />);
				imgCols.push(img);
			});
			const div=(<div key={k} className="ui tiny images" style={{marginTop:10,height:this.props.imgMaxHeight}}>{imgCols}</div>);
			divRows.push(div);
			k++;
		});
		//上一页，下一页
		let pagePre='';
		if(this.props.pageMaxIdArr.size>0){
			pagePre=(<span onClick={(e)=>this.prePage(e)} style={{cursor:'pointer'}}>上一页</span>);
		}
		let pageNext=(<span onClick={(e)=>this.nextPage(e)} style={{cursor:'pointer',marginLeft:10}}>下一页</span>);
		if(this.props.datalist.size==0 || this.props.datalist.size<this.pageNum){
			pageNext='';
		}

		return(
			<div>
				{divRows}
				<div style={{marginTop:10,textAlign:'right'}}>{pagePre}{pageNext}</div>
			</div>
		);
	}

} */